Fortran For Fun之常用字符处理函数

Fortran的字符串处理功能比较差,只提供一些非常简单的字符串处理函数。常用的有

  • achar(i)
    返回ASCII码为i的字符,常用的有

    1
    2
    3
    4
    achar(8) !< 退格符
    achar(9) !< 制表符
    achar(10) !< 换行符
    achar(13) !< 回车符
  • ichar(a)
    返回字符的ASCII码

  • adjustl(s)
    字符向左调整
  • adjustr(s)
    字符向右调整
  • trim(s)
    去掉字符后面的空格,通常和adjustl结合使用,trim(adjustl(s))
  • len(s)
    返回字符的长度
  • repeat(s,n)
    重复s,n次
  • new_line(‘a’)
    开始新的一行,相当于achar(10)
  • index(s,ss,[back])
    返回ss在s中第一次出现的位置
  • scan(s,ss,[back])
    返回ss中任意字符在s中出现的位置
  • verify(s,ss,[back])
    返回s中第一次出现不属于ss中字符的位置

learn_char

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
program learn_char
use, intrinsic :: iso_fortran_env, only: iostat_end
implicit none
character(99) :: line
integer :: ierr, unit
open(newunit=unit,status='scratch')
write(unit,*) '!'//repeat('=',40) &
& //new_line('a')//'! this is fortran comment' &
& //new_line('a')//'; this is python inline comment' &
& //new_line('a')//'# this is python comment' &
& //achar(10)//' 0 1.0 2.0E-5 +3.2'
rewind(unit)
do
read(unit,'(a)',iostat = ierr) line
if(ierr == iostat_end) exit
if(is_comments(line)) print'(a,t50, a)', trim(adjustl(line)), '!< comment line; '
if(is_number(line)) print'(a,t50, a)', trim(adjustl(line)), '!< number line; '
enddo
close(unit=unit)
contains
pure function is_fortran_comment(s) result(r)
character(*), intent(in) :: s
logical :: r
r = .FALSE.
if (index(trim(adjustl(s)), '!') == 1) r = .TRUE.
end function is_fortran_comment
pure function is_comments(s) result(r)
character(*), intent(in) :: s
logical :: r
r = .FALSE.
if (scan(trim(adjustl(s)), '!#;') == 1) r = .TRUE.
end function is_comments
pure function is_number(s) result(r)
character(*), intent(in) :: s
logical :: r
r = .TRUE.
if(verify(trim(adjustl(s)), '+-.0123456789E ' ) /= 0) r = .FALSE.
end function is_number
end program learn_char

结果

1
2
3
4
5
!======================================== !< comment line;
! this is fortran comment !< comment line;
; this is python inline comment !< comment line;
# this is python comment !< comment line;
0 1.0 2.0E-5 +3.2 !< number line;